import 'package:flutter/foundation.dart';
import 'package:loxen/api/api.dart';
import 'package:loxen/api/http_util.dart';
import 'package:loxen/mode/forget_pwd_model.dart';
import 'package:loxen/mode/code.dart';
import 'package:loxen/viewmode/base_view_model.dart';
import 'package:rxdart/rxdart.dart';

class CallBack {
  final void Function() onSuccess;
  final void Function(Exception error) onError;

  const CallBack(this.onSuccess, this.onError);
}

class ForgetPwdViewModel extends BaseViewModel {
  CallBack _callBack;

  set callBack(CallBack value) {
    _callBack = value;
  }

  void code(String mobile, String action,
      {void Function() onSuccess, void Function(String error) onFail}) {
    print(mobile);
    ApiService.code(mobile, action).listen((event) {
      if (event.statusCode == 201) {
        print(event.data);
        if (onSuccess != null) onSuccess.call();
      } else {
        if (onFail != null) onFail.call('未知异常');
      }
    }, onError: (error) {
      if (onFail != null) {
        if (error is ServiceException) {
          var data = error.userMessage;
          if (data is Map) {
            onFail.call(data["mobile"].toString());
          }
        }
      }
    });
  }
  void vacode(String mobile, String action,String code,
      {void Function() onSuccess, void Function(String error) onFail}) {
    print(mobile);
    ApiService.vacode(mobile, action,code).listen((event) {
      if (event.statusCode == 200) {
        print(event.data);
        if (onSuccess != null) onSuccess.call();
      } else {
        _callBack.onError(Exception('未知异常'));
        if (onFail != null) onFail.call('未知异常');
      }
    }, onError: (error) {
      if (onFail != null) {
        if (error is ServiceException) {
          var data = error.userMessage;
          if (data is Map) {
            onFail.call(data["mobile"].toString());
          }
        }
      }
    });
  }
  void forget(String mobile, String password, String code,
      {void Function() onSuccess, void Function(String error) onFail}) {
    ApiService.forget(mobile, password, code)
        .flatMap((value) => compute(decodeCode, value.data).asStream())
        .listen((event) {
      if (event.code == 2000) {

        if (onSuccess != null) onSuccess.call();
      } else {
        _callBack.onError(Exception('未知异常'));
        if (onFail != null) onFail.call('未知异常');
      }
    }, onError: (error) {
      if (onFail != null) {
        if (error is ServiceException) {
          var data = error.userMessage;
          print(data);
          if (data is Map) {
            onFail.call(data["mobile"].toString());
          }
        }
      }
    });
  }

  static Roots decodeCode(dynamic json) {
    return Roots.fromJson(json);
  }

  static Root decodeForget(dynamic json) {
    return Root.fromJson(json);
  }
}
